﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xms.CRM.Domain;

namespace Xms.MQ
{
    public static class LIMRepository
    {
        /// <summary>
        /// 获取当前用户的初始化数据
        /// </summary>
        /// <param name="userId">当前用户id</param>
        /// <returns></returns>
        public static LIMInitDoEntity GetInitData(int userId)
        {
            LIMInitDoEntity initdata = new LIMInitDoEntity();
            initdata.data.mine = new LIMMemberInfo();
            string sql = @"select UserId id,Name username,Signature sign,Avator avatar from  [SystemUser]";
            DataTable dt = SQLServerHelper.QueryForDataTatable(sql);
            LIMFriendInfo friend = new LIMFriendInfo();
            friend.id = 1;
            friend.groupname = "时代精英";
            foreach (DataRow item in dt.Rows)
            {
                if (int.Parse(item["id"].ToString()) == userId)
                {
                    initdata.data.mine.id = userId;
                    initdata.data.mine.username = item["username"].ToString();
                    initdata.data.mine.status = "online";
                    initdata.data.mine.sign = item["sign"].ToString(); ;
                    initdata.data.mine.avatar = item["avatar"].ToString();
                }
                LIMMemberInfo mem = new LIMMemberInfo();
                mem.id = int.Parse(item["id"].ToString());
                mem.username = item["username"].ToString();
                mem.sign = item["sign"].ToString();
                mem.avatar = item["avatar"].ToString();
                friend.list.Add(mem);
            }
            initdata.data.friend.Add(friend);//获取所有的好友
            initdata.data.group = GetUserRoomList(userId);//获取所有的群组聊天室
            return initdata;
        }
        public static List<LIMGroupInfo> GetUserRoomList(int userId)
        {
            List<LIMGroupInfo> grouplist = new List<LIMGroupInfo>();
            string groupstr = @"select r.RoomId,r.RoomName,r.RoomAvatar from[RoomMember] m
                        inner join[Room] r on m.RoomId=r.RoomId
                        where m.UserId=@UserId";
            List<SqlParameter> parameters = new List<SqlParameter>();
            parameters.Add(new SqlParameter() { ParameterName = "@UserId", SqlDbType = SqlDbType.VarChar, Value = userId });
            DataTable gdt = SQLServerHelper.QueryForDataTatable(groupstr, parameters);
            foreach (DataRow item in gdt.Rows)
            {
                LIMGroupInfo groupInfo = new LIMGroupInfo();
                groupInfo.id = int.Parse(item["RoomId"].ToString());
                groupInfo.groupname = item["RoomName"].ToString();
                groupInfo.avatar = item["RoomAvatar"].ToString();
                grouplist.Add(groupInfo);
            }
            return grouplist;
        }
        public static RoomMemberDoEntity GetRoomMember(int id)
        {
            RoomMemberDoEntity doEntity = new RoomMemberDoEntity();
            doEntity.data = new RoomMemberList();
            doEntity.data.list = new List<LIMMemberInfo>();
            string sql = @"  select u.UserId,u.Name UserName,u.Avator UserAvatar,u.Signature UserSign from [RoomMember] r
                              inner join [SystemUser] u on r.UserId=u.UserId
                              where r.RoomId=@RoomId";

            List<SqlParameter> parameters = new List<SqlParameter>();
            parameters.Add(new SqlParameter() { ParameterName = "@RoomId", SqlDbType = SqlDbType.VarChar, Value = id });
            DataTable dt = SQLServerHelper.QueryForDataTatable(sql, parameters);
            foreach (DataRow item in dt.Rows)
            {
                LIMMemberInfo mem = new LIMMemberInfo();
                mem.id = int.Parse(item["UserId"].ToString());
                mem.username = item["UserName"].ToString();
                mem.sign = item["UserSign"].ToString();
                mem.avatar = item["UserAvatar"].ToString();
                doEntity.data.list.Add(mem);
            };
            return doEntity;
        }

        public static List<UserTreeDoEntity> GetAllUser()
        {
            List<UserTreeDoEntity> list = new List<UserTreeDoEntity>();
            UserTreeDoEntity allentity = new UserTreeDoEntity();
            string sql = $@"select UserId id,Name username from  [SystemUser] order by Name";
            DataTable dt = SQLServerHelper.QueryForDataTatable(sql);
            allentity.children = new List<UserTreeDoEntity>();
            foreach (DataRow item in dt.Rows)
            {
                UserTreeDoEntity entity = new UserTreeDoEntity();
                entity.title = item["username"].ToString();
                entity.id = int.Parse(item["id"].ToString());
                allentity.children.Add(entity);
            }
            allentity.title = "所有成员";
            list.Add(allentity);
            return list;
        }
        public static UserDoEntity GetUser(string username, string password)
        {
            string sql = $@"select UserId id,Name username from  [SystemUser] where Name='{username}' and Password='{password}'";
            DataTable dt = SQLServerHelper.QueryForDataTatable(sql);

            UserDoEntity entity = new UserDoEntity();

            foreach (DataRow item in dt.Rows)
            {
                entity.UserName = item["username"].ToString();
                entity.UserId = int.Parse(item["id"].ToString());
            }
            return entity;
        }


        /// <summary>
        /// 消息列表
        /// </summary>
        /// <param name="meglist"></param>
        public static void SaveMessage(List<MessageEntity> meglist)
        {
            string sql = @"insert into [Message](FUserId,TUserId,SendTime,MessageContent)";
            string selectstr = " ";
            for (int i = 0; i < meglist.Count; i++)
            {
                if (i == 0)
                {
                    selectstr += $"select {meglist[i].FUserId},{meglist[i].TUserId},'{meglist[i].SendTime}','{meglist[i].MessageContent}'";
                    continue;
                }
                selectstr += $" union select { meglist[i].FUserId},{meglist[i].TUserId},'{meglist[i].SendTime}','{meglist[i].MessageContent}'";
            }
            if (selectstr != "")
            {
                sql += selectstr;
                SQLServerHelper.ExecuteSql(sql);
            }
        }
        /// <summary>
        /// 消息列表
        /// </summary>
        /// <param name="meglist"></param>
        public static void SaveRoomchat(List<MessageEntity> meglist)
        {
            string sql = @"insert into [RoomChat](UserId,RoomId,ChatTime,ChatContent)";
            string selectstr = " ";
            for (int i = 0; i < meglist.Count; i++)
            {
                if (i == 0)
                {
                    selectstr += $"select {meglist[i].FUserId},{meglist[i].TUserId},'{meglist[i].SendTime}','{meglist[i].MessageContent}'";
                    continue;
                }
                selectstr += $" union select { meglist[i].FUserId},{meglist[i].TUserId},'{meglist[i].SendTime}','{meglist[i].MessageContent}'";
            }
            if (selectstr != "")
            {
                sql += selectstr;
                SQLServerHelper.ExecuteSql(sql);
            }
        }
        /// <summary>
        /// 添加好友分组
        /// </summary>
        /// <returns></returns>
        public static void AddGroup(FriendGroupEntity friendGroup)
        {
            string sql = @"insert into [FriendGroup] (GroupName,GroupCreator,CreateTime) values('@GroupName',@GroupCreator,'@CreateTime')";
            SqlParameter[] parameters =
            {
                new SqlParameter() { ParameterName = "@GroupCreator", SqlDbType = SqlDbType.Int, Value = friendGroup.GroupCreator },
                new SqlParameter() { ParameterName = "@GroupName", SqlDbType = SqlDbType.VarChar, Value = friendGroup.GroupName },
                new SqlParameter() { ParameterName = "@CreateTime", SqlDbType = SqlDbType.DateTime, Value = friendGroup.CreateTime }
            };
            SQLServerHelper.ExecuteSql(sql, parameters);
        }
        /// <summary>
        /// 添加分组成员
        /// </summary>
        /// <returns></returns>
        public static void AddGroupMember(int groupid, int userid)
        {
            string sql = @"insert into [FriendGroup] (GroupId,UserId,AddTime) values(@GroupId,@UserId,'@AddTime')";
            SqlParameter[] parameters =
            {
                new SqlParameter() { ParameterName = "@GroupId", SqlDbType = SqlDbType.Int, Value = groupid },
                new SqlParameter() { ParameterName = "@UserId", SqlDbType = SqlDbType.VarChar, Value =userid },
                new SqlParameter() { ParameterName = "@AddTime", SqlDbType = SqlDbType.DateTime, Value = DateTime.Now }
            };
            SQLServerHelper.ExecuteSql(sql, parameters);
        }
        /// <summary>
        /// 添加聊天室
        /// </summary>
        /// <returns></returns>
        public static void AddChatRoom(RoomEntity roomEntity, List<int> memberlist = null)
        {
            string sql = @"insert into [Room](RoomName,Creator) values(@RoomName,@Creator) select @@identity";
            List<SqlParameter> parameters = new List<SqlParameter>();
            parameters.Add(new SqlParameter() { ParameterName = "@RoomName", SqlDbType = SqlDbType.VarChar, Value = roomEntity.RoomName });
            parameters.Add(new SqlParameter() { ParameterName = "@Creator", SqlDbType = SqlDbType.Int, Value = roomEntity.Creator });
            string identid = SQLServerHelper.ExecuteScalar(sql, parameters).ToString();
            int roomid = int.Parse(identid);
            string sqlmember = $"SET IDENTITY_INSERT [RoomMember]  ON insert into [RoomMember](RoomId,UserId) select {roomid},{roomEntity.Creator}";
            if (memberlist != null)
            {
                for (int i = 0; i < memberlist.Count; i++)
                {
                    if (roomEntity.Creator != memberlist[i])//排除自己
                    {
                        sqlmember += $" union select {roomid},{memberlist[i]}";
                    }
                }

            }
            SQLServerHelper.ExecuteSql(sqlmember);
        }
        /// <summary>
        /// 添加聊天室成员
        /// </summary>
        /// <returns></returns>
        public static void AddChatRoomMember(int roomid, int userid)
        {
            string sql = @"insert into [RoomMember](RoomId,UserId) values(@RoomId,@UserId)";
            SqlParameter[] parameters =
            {
                new SqlParameter() { ParameterName = "@RoomId", SqlDbType = SqlDbType.Int, Value = roomid },
                new SqlParameter() { ParameterName = "@UserId", SqlDbType = SqlDbType.VarChar, Value =userid },
            };
            SQLServerHelper.ExecuteSql(sql, parameters);
        }
        /// <summary>
        /// 获取单个聊天记录
        /// </summary>
        /// <param name="fid">发送者</param>
        /// <param name="tid">接收者</param>
        /// <returns></returns>
        public static ChatLogDoEntity GetMessageChatLog(int fid, int tid, string type, string sreachstr, long befortime)
        {
            ChatLogDoEntity doEntity = new ChatLogDoEntity();
            string sql = @"  select fu.UserId id,fu.Name username,fu.Avator avatar, m.SendTime times,m.MessageContent content,(CASE WHEN m.FUserId =@FUserId THEN 'True' ELSE 'False' END) mine
                          from [Message] m
                          inner join [SystemUser] fu on m.FUserId=fu.UserId
                          inner join [SystemUser] tu on m.TUserId=tu.UserId
                          where ((m.FUserId=@FUserId and m.TUserId=@TUserId) or(m.FUserId=@TUserId  and m.TUserId=@FUserId)) and m.MessageContent like @Content
                          order by m.MessageId ";
            if (type == "group")
            {
                sql = @"  select fu.UserId id,fu.Name username,fu.Avator avatar, r.ChatTime times,r.ChatContent content,(CASE WHEN fu.UserId =@FUserId THEN 'True' ELSE 'False' END) mine 
                          from [RoomChat] r
                          inner join [SystemUser] fu on r.UserId=fu.UserId
                          where r.RoomId=@TUserId and r.ChatContent like @Content
                          order by r.ChatId";
            }
            List<SqlParameter> parameters = new List<SqlParameter>();
            parameters.Add(new SqlParameter() { ParameterName = "@FUserId", SqlDbType = SqlDbType.VarChar, Value = fid });
            parameters.Add(new SqlParameter() { ParameterName = "@TUserId", SqlDbType = SqlDbType.Int, Value = tid });
            parameters.Add(new SqlParameter() { ParameterName = "@Content", SqlDbType = SqlDbType.VarChar, Value = $"%{sreachstr}%" });
            DataTable dt = SQLServerHelper.QueryForDataTatable(sql, parameters);
            int tmpnum = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                MessageDoEntity message = new MessageDoEntity();
                message.id = dt.Rows[i]["id"].ToString();
                message.mine = bool.Parse(dt.Rows[i]["mine"].ToString());
                message.username = dt.Rows[i]["username"].ToString();
                message.content = dt.Rows[i]["content"].ToString();
                message.avatar = dt.Rows[i]["avatar"].ToString();
                message.timestamp = CommonHelper.GetTimeSpan(DateTime.Parse(dt.Rows[i]["times"].ToString()));

                if (sreachstr != "" && befortime == 0)//不是查询前后消息，只是搜索
                {
                    message.beforemsg = "查看前后消息";
                }
                else
                {
                    message.beforemsg = "";
                }
                doEntity.data.Add(message);
                if (befortime == message.timestamp && befortime > 0)//记录查找的时间戳
                {
                    tmpnum = i;
                }
                if (tmpnum > 0)//假如记录了时间戳，再多取3条
                {
                    if (i > (tmpnum + 3))
                    {
                        break;
                    }
                }
            }
            if (tmpnum > 0)
            {
                int beforcount = 3;
                int startindex = 0;
                if ((tmpnum - 3) > 0)//假如前面有三条，则从前三条的索引开始否则从0开始
                {
                    startindex = tmpnum - 3;
                }
                else
                {
                    beforcount = tmpnum;
                }
                int aftercont = (doEntity.data.Count - tmpnum) < 3 ? (doEntity.data.Count - tmpnum) : 3;//假如后面小于3条则返回条数，否则返回3
                doEntity.data = doEntity.data.GetRange(startindex, beforcount + aftercont);
            }
            return doEntity;
        }
    }
}
